<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 搜索form -->
        <searchForm
          :question="Ischoice"
          @getChoiceNewTableData="getChoiceNewTableData"
          @fn="search"
        />
        <div class="box">
          <!-- 页签 -->
          <el-tabs
            v-model="activeName"
            type="card"
            @tab-click="handleClick"
            style="margin-top: 15px"
          >
            <el-tab-pane label="全部" name="3" @tab-click="activeName = '3'" />
            <el-tab-pane
              label="待审核"
              name="0"
              @tab-click="activeName = '0'"
            />
            <el-tab-pane
              label="已审核"
              name="1"
              @tab-click="activeName = '1'"
            />
            <el-tab-pane
              label="已拒绝"
              name="2"
              @tab-click="activeName = '2'"
            />
          </el-tabs>
          <el-button type="success" icon="el-icon-edit" @click="exportEmployees"
            >批量导出</el-button
          >
        </div>

        <!-- 数据条数 -->
        <el-alert
          :title="'数据一共' + counts + '条'"
          type="info"
          show-icon
          :closable="false"
        />
        <!-- 试题表格 -->
        <el-table :data="tableData" style="width: 100%; margin-top: 20px">
          <el-table-column prop="number" label="试题编号" width="220" />
          <el-table-column prop="subject" label="学科" width="100" />
          <el-table-column prop="catalog" label="目录" width="120" />
          <el-table-column
            prop="questionType"
            label="题型"
            width="100"
            :formatter="formatterQuestionType"
          />
          <el-table-column prop="question" label="题干" width="270">
            <template slot-scope="scope">
              <p v-html="scope.row.question"></p>
            </template>
          </el-table-column>
          <el-table-column prop="addDate" label="录入时间" width="200">
            <template slot-scope="scope">
              {{ formatTime(scope.row.addDate) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="difficulty"
            label="难度"
            width="100"
            :formatter="formatterDifficulty"
          />
          <el-table-column prop="creator" label="录入人" width="150" />
          <el-table-column
            prop="chkState"
            label="审核状态"
            width="150"
            :formatter="formatterChkType"
          />
          <el-table-column prop="chkRemarks" label="审核意见" width="200" />
          <el-table-column prop="chkUser" label="审核人" width="120" />
          <el-table-column label="发布状态" width="120">
            <template slot-scope="{ row }">
              {{ formatterPublishType(row) }}
            </template>
          </el-table-column>
          <!-- 操作按钮 -->
          <el-table-column
            fixed="right"
            label="操作"
            width="230"
            align="center"
          >
            <template slot-scope="{ row }">
              <el-button type="text" @click.native="preview(row)"
                >预览</el-button
              >
              <el-button
                type="text"
                :disabled="row.chkState !== 0"
                @click.native="openCheckDialog(row)"
                >审核</el-button
              >
              <el-button
                type="text"
                :disabled="row.publishState === 1"
                @click.native="EditChoice(row)"
                >修改</el-button
              >
              <el-button type="text" @click.native="changePublishState(row)">{{
                row.publishState === 0 ? "上架" : "下架"
              }}</el-button>
              <el-button
                type="text"
                :disabled="row.publishState === 1"
                @click.native="delChoice(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="counts"
        >
        </el-pagination>
      </el-card>
      <!-- 题目审核弹窗 -->
      <el-dialog
        customClass="customWidth"
        title="题目审核"
        :visible="showDialogDialog"
        @close="closeDialogFn"
      >
        <el-form ref="checkForm" :model="checkFormData" class="demo-ruleForm">
          <el-form-item prop="chkState">
            <el-radio v-model="checkFormData.chkState" :label="1"
              >通过</el-radio
            >
            <el-radio
              v-model="checkFormData.chkState"
              :label="2"
              style="margin-left: 55px"
              >拒绝</el-radio
            >
          </el-form-item>
          <el-form-item prop="chkRemarks">
            <textarea
              autocomplete="off"
              placeholder="请输入审核意见"
              style="min-height: 32px"
              class="el-textarea__inner"
              v-model="checkFormData.chkRemarks"
            ></textarea>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialogFn">取 消</el-button>
          <el-button type="primary" @click="submitCheck">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 查看弹窗 -->
      <PreviewDialog
        :showDialog.sync="showDialog"
        :QuestionDetail="QuestionDetail"
      />
    </div>
  </div>
</template>

<script>
import searchForm from '@/components/searchForm' // 查询
import HintButton from '@/module-hmmm/pages/questuons/button.vue' // 封装的按钮
import PreviewDialog from '@/components/PreviewDialog' // 查看弹窗
import dayjs from 'dayjs' // 处理时间插件
import {
  questionType, // 题型
  difficulty, // 难度
  chkType // 审核状态
} from '@/api/hmmm/constants'
import {
  choice as getChoiceListApi, // 获取精选题库列表
  detail as getQuestionDetailApi, // 获取详情
  choiceCheck, // 试题审核
  remove as choiceDelApi, // 精选题库删除
  choicePublish as changeChoicePublishApi // 上下架
} from '@/api/hmmm/questions'
export default {
  components: {
    searchForm,
    HintButton,
    PreviewDialog
  },
  data () {
    return {
      // 审核弹窗表单数据
      checkFormData: {
        chkState: 1, // 审核是否通过
        chkRemarks: '', // 审核意见
        id: null // 提交审核时需要用到的id
      },
      QuestionDetail: {}, // 用来回显审核弹窗的数据
      showDialogDialog: false, // 控制审核弹窗显示
      Ischoice: true, // 传给搜索组件
      counts: null, // 数据条数
      activeName: '1', // 当前所在页签
      tableData: [], // 精选题库列表
      pagesize: null, // 总页码数
      counts: null, // 总条数
      pages: null, // 总页数
      page: 1, // 当前页
      pagesize: 10, // 每页多少条数据
      showDialog: false, // 控制弹窗显示和隐藏
      tableData: [], // 精选题库列表
      formDataAll: {}, // 搜索组件的搜索参数
      QuestionDetail: {} // 基础数据详情
    }
  },
  async created () {
    this.activeName = '3'
    await this.getChoiceList()
  },
  methods: {
    async exportEmployees() {
      // 请求后台数据
      let {data: { items },} = await getChoiceListApi();
      const headersArr = [
        "试题编号",
        "学科",
        "目录",
        "题干",
        "题型",
        "录入时间",
        "难度",
        "录入人",
        "审核状态",
      ];
      const headersRelations = {
        试题编号: "number",
        学科: "subject",
        目录: "catalog",
        题干: "remarks",
        题型: "questionType",
        录入时间: "addDate",
        难度: "difficulty",
        录入人: "departmentName",
        审核状态: "chkState",
      };
      // 调用封装好的处理数据函数
      let dataArr = this.formatJson(items, headersArr, headersRelations);
      // 执行导出
      import("@/vendor/Export2Excel").then((excel) => {
        excel.export_json_to_excel({
          header: headersArr, // 表头 必填
          data: dataArr, // 具体数据 必填
          // 导出的文件名
          filename: "基础题", // 非必填
          // 表格宽度是否自适应
          autoWidth: true, // 非必填
          // 导出文件的后缀名
          bookType: "xlsx", // 非必填
        });
      });
    },
    // 处理导出时请求回来的数据
    formatJson(rows, headersArr, headersRelations) {
      let newArr = [];
      rows.forEach((itme) => {
        let tempArr = [];
        headersArr.forEach((key) => {
          const english = headersRelations[key];
          let val = itme[english];
          // 处理时间格式
          if (["addDate"].includes(english)) {
            val = this.formatTime(val);
          }
          // 处理聘用形式
          if (english === "questionType") {
            // 获取枚举里面的聘用数组
            // let hireType = enumObj.hireType;
            // 通过hireType.find找到后台返回的聘用形式对应的中文
            let res = questionType.find((i) => i.id === Number(itme[english]));
            val = res ? res.value : "未知";
          }
          tempArr.push(val);
        });
        newArr.push(tempArr);
      });
      return newArr;
    },
    // 上下架
    async changePublishState (row) {
      if (row.publishState === 1) {
        row.publishState = 0;
      } else {
        row.publishState = 1;
      }
      await changeChoicePublishApi(row);
    },
    // 删除按钮
    delChoice(row) {
      this.$confirm("此操作将永久删除该题目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await choiceDelApi(row);
          await this.getChoiceList();

          this.$message.success("删除成功");
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 修改按钮
    EditChoice(row) {
      this.$router.push(`/questions/new?id=${row.id}`);
    },
    // 确定提交审核
    submitCheck() {
      if (this.checkFormData.chkRemarks === "") {
        this.$message.success("请输入审核意见");
        return;
      }
      this.$confirm('是否提交审核', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await choiceCheck(this.checkFormData);
          if (this.activeName === "3") {
            await this.getChoiceList();
          } else {
            await this.getChoiceList({ chkState: 0 });
          }
          this.$message.success("提交成功");
          this.showDialogDialog = false;
          this.checkFormData.chkRemarks = "";
          this.checkFormData.id = null;
          // this.checkFormData = {
          //   chkState: 1, //审核是否通过
          //   chkRemarks: "", //审核意见
          //   id: null, //提交审核时需要用到的id
          // };
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消审核'
          })
        })
      console.log(this.checkFormData)
    },
    // 打开弹窗
    openCheckDialog (row) {
      this.showDialogDialog = true
      this.checkFormData.id = row.id
    },
    // 关闭审核弹窗
    closeDialogFn () {
      this.showDialogDialog = false
      this.checkFormData = {
        chkState: 1, // 审核是否通过
        chkRemarks: '', // 审核意见
        id: null // 提交审核时需要用到的id
      }
    },
    // 页签切换功能
    async handleClick (tab, event) {
      if (this.activeName === '3') {
        this.getChoiceList()
      } else {
        this.getChoiceList({ chkState: Number(this.activeName) })
      }
    },
    // 预览功能
    async preview (row) {
      const { data } = await getQuestionDetailApi({ id: row.id })
      this.showDialog = true
      this.QuestionDetail = data
    },
    // 接受搜索组件传过来的搜索参数
    search (val) {
      this.formDataAll = val
    },
    // 获取筛选后的数据
    getChoiceNewTableData (data) {
      this.tableData = data.items
      this.counts = data.counts
    },
    // 当前页发生改变
    handleCurrentChange (val) {
      this.page = val
      const obj = { ...this.formDataAll, page: this.page }
      this.getChoiceList(obj)
    },
    // 每页条数
    handleSizeChange (val) {
      this.pagesize = val
      this.page = 1
      const obj = {
        ...this.formDataAll,
        page: this.page,
        pagesize: this.pagesize
      }
      this.getChoiceList(obj)
    },
    // 处理发布状态函数
    formatterPublishType (row) {
      if (row.publishState === 1 && row.chkState === 1) {
        return '已发布'
      }
      if (row.publishState === 0 && row.chkState === 1) {
        return '已下架'
      }
      return '待发布'
    },
    // 处理审核状态函数
    formatterChkType (row, column, cellValue, index) {
      const res = chkType.find((itme) => itme.value == cellValue)
      if (res === undefined) return
      return res.label
    },
    // 处理难度函数
    formatterDifficulty (row, column, cellValue, index) {
      const res = difficulty.find((itme) => itme.value === cellValue)
      if (res === '' || res === undefined) return
      return res.label
    },
    // 处理题型函数
    formatterQuestionType (row, column, cellValue, index) {
      const res = questionType.find((itme) => itme.value === cellValue)
      if (res === '' || res === undefined) return
      return res.label
    },
    // 处理时间函数
    formatTime (data) {
      return dayjs(data).format('YYYY-MM-DD HH:mm:ss')
    },
    // 获取精选题库列表
    async getChoiceList (searchForm) {
      const { data } = await getChoiceListApi(searchForm)
      this.tableData = data.items
      this.counts = data.counts
    }
  }
  // tableData: {
  //   deep: true, // 每层数据监听，深度监听
  //   handler() {
  //     // handler处理器：当数据变化时，要执行的函数！
  //     return this.tableData;
  //   },
  // },
}
</script>

<style scoped lang="scss">
.el-textarea__inner {
  display: block;
  resize: vertical;
  padding: 5px 15px;
  line-height: 1.5;
  box-sizing: border-box;
  width: 100%;
  font-size: inherit;
  color: #606266;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
.box {
  margin-bottom: 5px;
  display: flex;
  justify-content: space-between;
}
::v-deep {
  .customWidth {
    width: 450px !important;
  }
}
</style>
